package it.bifulco.luigi.motiondetection.prototype;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.security.MessageDigest;

import javax.imageio.ImageIO;

public class ImageUtils {

	public static String image2MD5(BufferedImage img) throws Exception {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ImageIO.write(img, "jpg", outputStream);
		byte[] data = outputStream.toByteArray();

		System.out.println("Start MD5 Digest");
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(data);
		byte[] hash = md.digest();
		String md5 = returnHex(hash);
		System.out.println(md5);
		return md5;
	}

	static String returnHex(byte[] inBytes) throws Exception {
		String hexString = null;
		for (int i = 0; i < inBytes.length; i++) { // for loop ID:1
			hexString += Integer.toString((inBytes[i] & 0xff) + 0x100, 16)
					.substring(1);
		} // Belongs to for loop ID:1
		return hexString;
	}
}
